package com.grantha.listner;

import java.io.IOException;
import java.util.Properties;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;

import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;

import com.grantha.util.Constants;
import com.grantha.util.DB;
import com.grantha.util.StartupConstants;

public class ContextListener implements ServletContextListener {

	private static Logger logger = Logger.getLogger(ContextListener.class);
	private static final String ATTRIBUTE_NAME = "config";
	private Properties config = new Properties();

	public void contextDestroyed(ServletContextEvent arg0) {

		// destroy method

	}

	public void contextInitialized(ServletContextEvent arg0) {

		try {
			DOMConfigurator.configure(arg0.getServletContext().getRealPath(
					"WEB-INF/log4j.xml"));
			logger.info("Logger initialized");

		} catch (Exception e1) {
			logger.error("Error initializing the shedular services.", e1);
		}

		try {
			config.load(Thread.currentThread().getContextClassLoader()
					.getResourceAsStream("config.properties"));
			logger.info("Property bundle loaded");
		} catch (IOException e) {
			logger.error("Loading config failed", e);
		}
		arg0.getServletContext().setAttribute(ATTRIBUTE_NAME, this);

		setStarupConstants();

		DB.init(StartupConstants.getDbName(), StartupConstants.getDbIP(),
				StartupConstants.getDbUserName(),
				StartupConstants.getDbPassword());

		logger.info("##################   Context Listner Loading Completed  #################");

	}

	public void setStarupConstants() {
		try {
			StartupConstants.setDbName(config.getProperty(Constants.DB_NAME));
			StartupConstants.setDbIP(config.getProperty(Constants.DB_IP));
			StartupConstants.setDbUserName(config
					.getProperty(Constants.DB_USERNAME));
			StartupConstants.setDbPassword(config
					.getProperty(Constants.DB_PASSWORD));
			
			StartupConstants.createLibrary();

			logger.info("constants initialization success");
		} catch (Exception e) {
			logger.error("An exception occured while Initializing startup constants\n"
					+ e);
		}
	}

}
